package com.explore.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.explore.demo.DTO.SearchDTO;
import com.explore.demo.VO.CompanyInfoVO;
import com.explore.demo.VO.RecruitmentInfoVO;
import com.explore.demo.cache.RedisCache;
import com.explore.demo.common.ResultCode;
import com.explore.demo.common.ServerResponse;
import com.explore.demo.config.JwtConfig;
import com.explore.demo.mapper.*;
import com.explore.demo.pojo.*;
import com.explore.demo.service.RecruitmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.explore.demo.utils.IPUtils;
import com.sun.rowset.internal.Row;
import io.swagger.models.auth.In;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gaolainan
 * @since 2021-04-18
 */
@Service
public class RecruitmentServiceImpl extends ServiceImpl<RecruitmentMapper, Recruitment> implements RecruitmentService
{

    /**
     * 打印日志文件
     */
    private final Logger logger = LoggerFactory.getLogger(RecruitmentServiceImpl.class);

    @Resource
    private RowViewMapper rowViewMapper;

    @Resource
    private RecruitmentMapper recruitmentMapper;

    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private WelfareCategoryMapper welfareCategoryMapper;

    @Resource
    private RecruitCategoryMapper recruitCategoryMapper;

    @Resource
    private JwtConfig jwtConfig;

    @Resource
    private HumanSourceMapper humanSourceMapper;

    @Resource
    private IPUtils ipUtils;

    @Resource
    private RedisCache redisCache;

    @Override
    public ServerResponse addRecruitment(Recruitment recruitment, HttpServletRequest request)
    {
        if (recruitment == null){
            return ServerResponse.createBySuccessMessage(ResultCode.RECRUITMENT_IS_NULL.getDescription(),
                                                         ResultCode.RECRUITMENT_IS_NULL.getCode(),
                                                         null);
        }
        String token =  request.getHeader(jwtConfig.getHeader());
        String phone = jwtConfig.getUsernameFromToken(token);
        HumanSource humanSource = humanSourceMapper.selectOne(new QueryWrapper<HumanSource>().eq("phone", phone));
        synchronized (this){
            recruitment.setHumanSourceId(humanSource.getId());
            recruitment.setCompanyId(humanSource.getDepartmentId());
            int res = recruitmentMapper.insert(recruitment);
            if (res == 0){
                return ServerResponse.createBySuccessMessage("fail to insert recruitment", 2000, null);
            }
            Recruitment newRecruitment = recruitmentMapper.getNewRecruitment();
            RowView rowView = new RowView();
            rowView.setRecruitId(newRecruitment.getId()).setCompanyId(newRecruitment.getCompanyId()).setReadNum(0).setCommentNum(0).setCollectNum(0);
            int insert = rowViewMapper.insert(rowView);

            return  insert == 0 ?
                    ServerResponse.createBySuccessMessage("system error", 2000, null):
                    ServerResponse.createBySuccessMessage("success", 200, null);
        }
    }

    @Override
    public ServerResponse deleteByTitle(Integer id)
    {
        if (id == null){
            return ServerResponse.createBySuccessMessage(ResultCode.RECRUITMENT_TITLE_IS_NULL.getDescription(),
                                                         ResultCode.RECRUITMENT_TITLE_IS_NULL.getCode(),
                                                         null);
        }
        return recruitmentMapper.deleteById(id) != 0?
               ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(),
                                                     ResultCode.SUCCESS.getCode(),
                                                     null):
               ServerResponse.createBySuccessMessage(ResultCode.RECRUITMENT_DELETE_FAIL.getDescription(),
                                                     ResultCode.RECRUITMENT_DELETE_FAIL.getCode(),
                                                     null);
    }

    @Override
    public ServerResponse queryAll()
    {
        QueryWrapper<Recruitment> wrapper = new QueryWrapper<>();
        wrapper
                .ge("id",1);
        return ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(),
                                                     ResultCode.SUCCESS.getCode(),
                                                     recruitmentMapper.selectList(wrapper));
    }

    @Override
    public ServerResponse queryByTitle(String title)
    {
        if (title == null){
            return ServerResponse.createBySuccessMessage(ResultCode.RECRUITMENT_TITLE_IS_NULL.getDescription(),
                                                         ResultCode.RECRUITMENT_TITLE_IS_NULL.getCode(),
                                                         null);
        }
        QueryWrapper<Recruitment> wrapper = new QueryWrapper<>();
        wrapper
                .eq("title",title);
        return ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(),
                                                     ResultCode.SUCCESS.getCode(),
                                                     recruitmentMapper.selectList(wrapper));
    }

    @Override
    public ServerResponse queryByRecruitmentId(@NotNull Integer recruitmentId, HttpServletRequest request)
    {
        /// System.out.println(request.getRequestURL());
        System.out.println(ipUtils.getIpAddr(request));
        String ipAddr = ipUtils.getIpAddr(request);
        if (redisCache.hasKey(ipAddr)){
            List<Integer> cacheObject = redisCache.getCacheObject(ipAddr);
            if (!cacheObject.contains(recruitmentId)){
                RowView rowView = rowViewMapper.selectOne(new QueryWrapper<RowView>().eq("recruit_id", recruitmentId));
                synchronized (this){
                    int count = rowView.getReadNum();
                    rowView.setReadNum(count+1);
                }
                int update = rowViewMapper.updateById(rowView);
                logger.info("浏览量增加与否：==================================> "+update);
            }

        }else{
            List<Integer> list = new ArrayList<>();
            RowView rowView = rowViewMapper.selectOne(new QueryWrapper<RowView>().eq("recruit_id", recruitmentId));
            synchronized (this){
                int count = rowView.getReadNum();
                rowView.setReadNum(count+1);
            }
            int update = rowViewMapper.updateById(rowView);
            logger.info("浏览量增加与否：==================================> "+update);
            list.add(recruitmentId);
            redisCache.setCacheObject(ipAddr, list, 10, TimeUnit.MINUTES);
        }

        // QueryWrapper<Recruitment> wrapper = new QueryWrapper<>();
        // wrapper.eq("id", recruitmentId);
        logger.info("职位的id为：---------------------------------》"+recruitmentId);
        Recruitment recruitment = recruitmentMapper.selectOne(new QueryWrapper<Recruitment>().eq("id", recruitmentId));
        // QueryWrapper<Company> queryWrapper = new QueryWrapper<>();
        // queryWrapper.eq("id", recruitment.getCompanyId());
        logger.info("职位的内容-----------------------------------》"+recruitment.toString());
        Company company = companyMapper.selectOne(new QueryWrapper<Company>().eq("id", recruitment.getCompanyId()));
        CompanyInfoVO companyInfoVO = new CompanyInfoVO();
        companyInfoVO.setLogo(company.getCompanyLogo())
                     .setCompanyName(company.getCompanyName())
                     .setStatus(company.getStatus())
                     .setCompanyCategory(companyMapper.getCategoryName(company.getId()))
                     .setRecruitCounts(company.getId());
        QueryWrapper<RowView> rowViewQueryWrapper = new QueryWrapper<>();
        rowViewQueryWrapper.eq("recruit_id", recruitmentId);
        RowView rowView = rowViewMapper.selectOne(rowViewQueryWrapper);
        //if (rowView != null){
            RecruitmentInfoVO recruitmentInfoVO = new RecruitmentInfoVO();
            recruitmentInfoVO.setRecruitment(recruitment)
                             .setCompanyInfoVO(companyInfoVO)
                             .setReadNum(rowView.getReadNum())
                             .setCollectNum(rowView.getCollectNum())
                             .setWelfareCategory(recruitmentMapper.getAllWelfareCategory(recruitmentId))
                             .setCommentNum(rowView.getCommentNum());

            return ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(),
                                                         ResultCode.SUCCESS.getCode(),
                                                         recruitmentInfoVO);
       // }
        // RowView tmp = new RowView();
        // tmp.setRecruitId(recruitment.getId())
        //    .setCompanyId(recruitment.getCompanyId())
        //    .setReadNum(0)
        //    .setCollectNum(0)
        //    .setCommentNum(0);
        // int insert = rowViewMapper.insert(tmp);
        // logger.info("数据插入的结果为： ======> "+ insert);
        // RecruitmentInfoVO recruitmentInfoVO = new RecruitmentInfoVO();
        // recruitmentInfoVO.setRecruitment(recruitment)
        //                  .setCompanyInfoVO(companyInfoVO)
        //                  .setReadNum(tmp.getReadNum())
        //                  .setCollectNum(tmp.getCollectNum())
        //                  .setWelfareCategory(recruitmentMapper.getAllWelfareCategory(recruitmentId))
        //                  .setCommentNum(tmp.getCommentNum());
        //
        // return ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(),
        //                                              ResultCode.SUCCESS.getCode(),
        //                                              recruitmentInfoVO);
    }


    @Override
    public ServerResponse updateRecruitment(Recruitment recruitment)
    {
        if (recruitment == null){
            return ServerResponse.createBySuccessMessage(ResultCode.RECRUITMENT_IS_NULL.getDescription(),
                                                         ResultCode.RECRUITMENT_IS_NULL.getCode(),
                                                         null);
        }
        return recruitmentMapper.updateById(recruitment) != 0?
               ServerResponse.createBySuccessMessage(ResultCode.SUCCESS.getDescription(),
                                                     ResultCode.SUCCESS.getCode(),
                                                     null):
               ServerResponse.createBySuccessMessage(ResultCode.UPDATE_FAIL.getDescription(),
                                                     ResultCode.UPDATE_FAIL.getCode(),
                                                     null);
    }

    @Override
    public ServerResponse queryAllBySearchVO(SearchDTO searchDTO)
    {
        return ServerResponse.createBySuccessMessage("功能还在开发当中，敬请期待！");
    }

    @Override
    public ServerResponse createRecruitment(Recruitment recruitment, List<String> recruitCategory, List<String> welfareCategory,
            HttpServletRequest request)
    {
        String token =  request.getHeader(jwtConfig.getHeader());
        String phone = jwtConfig.getUsernameFromToken(token);
        HumanSource humanSource = humanSourceMapper.selectOne(new QueryWrapper<HumanSource>().eq("phone", phone));
        recruitment.setHumanSourceId(humanSource.getId());
        recruitment.setCompanyId(humanSource.getDepartmentId());
        int res = recruitmentMapper.insert(recruitment);
        if (res == 0){
            return ServerResponse.createBySuccessMessage("fail", 2000,null);
        }
        Recruitment tmp = recruitmentMapper.getNewRecruitment();
        RowView rowView = new RowView();
        rowView.setRecruitId(tmp.getId()).setCompanyId(tmp.getCompanyId());
        int insert = rowViewMapper.insert(rowView);
        if (insert == 0){
            return ServerResponse.createBySuccessMessage("row_view insert fail", 2000, null);
        }
        List<Integer> recruitList = new ArrayList<>();
        recruitCategory.forEach(recruitCategoryId -> recruitList.add(categoryMapper.getCategoryId(recruitCategoryId)));
        List<Integer> welfareList = new ArrayList<>();
        welfareCategory.forEach(recruitCategoryId -> welfareList.add(categoryMapper.getCategoryId(recruitCategoryId)));

        recruitList.forEach(temp -> recruitCategoryMapper.insert(new RecruitCategory().setCategoryId(temp).setRecruitId(tmp.getId())));
        welfareList.forEach(temp -> welfareCategoryMapper.insert(new WelfareCategory().setCategoryId(temp).setRecruitId(tmp.getId())));

        return ServerResponse.createBySuccessMessage("success", 200, null);
    }
}
